// 导入必要的包和类
package com.example.emos.wx.config.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

// 将类标记为Spring组件，并设置为原型范围
@Component
@Scope("prototype")
public class OAuth2Filter extends AuthenticatingFilter {

    // 自动注入ThreadLocalToken实例，用于在线程本地存储令牌
    @Autowired
    private ThreadLocalToken threadLocalToken;

    // 从配置文件中读取令牌缓存过期时间
    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;

    // 自动注入JwtUtil实例，用于JWT令牌的生成和验证
    @Autowired
    private JwtUtil jwtUtil;

    // 自动注入RedisTemplate实例，用于与Redis数据库交互
    @Autowired
    private RedisTemplate redisTemplate;

    // 重写方法以从请求中创建身份验证令牌
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        // 从请求中提取令牌
        String token = getRequestToken(req);
        if (StrUtil.isBlank(token)) {
            return null;
        }
        // 创建并返回OAuth2Token
        return new OAuth2Token(token);
    }

    // 重写方法以检查是否允许请求访问
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        // 允许OPTIONS请求
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }
        return false;
    }

    // 重写方法以处理拒绝访问的情况
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 为CORS设置响应头
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));

        // 清除线程本地令牌
        threadLocalToken.clear();

        // 获取并验证请求令牌
        String token = getRequestToken(req);
        if (StrUtil.isBlank(token)) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌"); // 无效的令牌消息
            return false;
        }
        try {
            jwtUtil.verifierToken(token);
        } catch (TokenExpiredException e) {
            // 处理令牌过期
            if (redisTemplate.hasKey(token)) {
                redisTemplate.delete(token);
                int userId = jwtUtil.getUserId(token);
                token = jwtUtil.createToken(userId);
                redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
                threadLocalToken.setToken(token);
            } else {
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().print("令牌已过期"); // 令牌已过期消息
                return false;
            }
        } catch (Exception e) {
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("无效的令牌"); // 无效的令牌消息
            return false;
        }

        // 在令牌验证后尝试登录
        boolean bool = executeLogin(request, response);
        return bool;
    }

    // 重写方法以处理登录失败
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 为CORS设置响应头
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
        try {
            resp.getWriter().print(e.getMessage());
        } catch (Exception exception) {

        }

        return false;
    }

    // 重写方法以处理内部过滤器逻辑
    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 调用父类方法进行过滤器处理
        super.doFilterInternal(request, response, chain);
    }

    // 辅助方法，从请求中获取令牌
    private String getRequestToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }
}
